from multiprocessing import Lock
from suds import metrics
import time
from Autotests.Suites.StressTest.Selector.OperationsGroupSelector import OperationGroups
from Config.RunConfig import RunConfig, Options


class GroupSwitchTimer:

    _groupExecutionTime = int(RunConfig().get(Options.StressTest.groupExecutionTime))
    _timerStart = time.time()
    _groupsCount = len(OperationGroups().operationsGroup)
    _currentIndex = 0

    mutex = Lock()

    @staticmethod
    def getGroupIndex():
        try:
            GroupSwitchTimer.mutex.acquire()

            currentExecutionTime = int(time.time() - GroupSwitchTimer._timerStart)

            if currentExecutionTime < GroupSwitchTimer._groupExecutionTime:
                return GroupSwitchTimer._currentIndex
            else:
                GroupSwitchTimer._currentIndex += 1
                GroupSwitchTimer._timerStart = time.time()

                if GroupSwitchTimer._currentIndex >= GroupSwitchTimer._groupsCount - 1:
                    GroupSwitchTimer._currentIndex = 0

                return GroupSwitchTimer._currentIndex
        finally:
            GroupSwitchTimer.mutex.release()
